<!--hxf-0730-将搜索框所需绑定值传递给子组件，绑定确定方法重置方法-->
<template>
  <div class="page-box">
    <v-step ref="steps" :milepost="milepost">
      <!-- 模板选择 -->
      <div slot="step0" class="importStep">
        <!-- 模板为空 -->
        <div class="templateUpload" v-if="!pdfUrl">
          <div class="icon">
            <i class="el-icon-document elIcon" />
          </div>
          <p>模板空空，赶紧导入...</p>
          <el-upload
            class="upload-demo"
            ref="upload"
            action="/admin/sys-file/upLodeFileAdd"
            :auto-upload="false"
            :file-list="fileList"
            :on-change="handleTemplateChange"
            accept=".doc, .docx, .pdf"
          >
            <el-button class="exportBtn" type="primary">开始导入</el-button>
            <div slot="tip" class="el-upload__tip">支持导入格式：doc,docx,pdf</div>
          </el-upload>
        </div>
        <!-- 模板不为空 -->
        <div class="templateShow" v-else>
          <div class="fileWrap" @click="previewTemplate">
            <pdf ref="pdf" :src="pdfUrl" :page="1" style="width: 100%" v-if="previewType == 'pdf'" />
            <div class="wordsWrap" v-else>
              <div class="name">
                <p>{{ fileList.length?fileList[0].name:''}}</p>
                <p>模板文件</p>
              </div>
              <div>
                <p>出租方：深圳市福田区物业管理中心</p>
                <p>承租方：{{formData.customerName || '暂无数据'}}</p>
              </div>
              <div class="date">合同签订日期：{{formData.endDate}}</div>
            </div>
          </div>
          <div class="fileWrap">
            <el-upload
              class="upload-demo"
              ref="upload"
              action="/admin/sys-file/upLodeFileAdd"
              :auto-upload="false"
              :file-list="fileList"
              :on-change="handleTemplateChange"
              accept=".doc, .docx, .pdf"
              :show-file-list="false"
            >
              <div class="add">
                <i class="icon el-icon-plus"></i>
                <div class="el-upload__tip">支持导入格式：doc,docx,pdf</div>
              </div>
            </el-upload>
          </div>
          <el-dialog title="合同详情" width="800px" :visible.sync="dialogContractVisible" :close-on-click-modal="false">
            <v-pdf :src="pdfUrl" />
          </el-dialog>
        </div>

        <el-form class="nameForm" size="small" :model="nameForm" ref="nameForm">
          <el-form-item label="合同名称:" prop="contractName">
            <el-input v-model="nameForm.contractName" placeholder="请输入合同名称" maxlength="20" />
          </el-form-item>
        </el-form>
      </div>
      <!-- 合同基本信息填写 -->
      <div slot="step1" class="step1">
        <div class="card-title">
          承租方信息
          <el-button type="primary" size="small" @click="$refs.clientSelect.show()">选择承租方</el-button>
        </div>

        <el-form class="basicPadding mt20" :model="propForm" size="small" ref="propForm">
          <el-row :gutter="30" style="text-align:left;">
            <el-col :span="6">
              <el-form-item label="承租方名称:">{{propForm.clientLesseeName}}</el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="承租方类型:">{{baseInfo.lessee}}</el-form-item>
            </el-col>
            <!-- 第一行第3列-->
            <el-col :span="6">
              <el-form-item v-show="propForm.clientLesseeType==0" label="证件类型:">{{baseInfo.personageCertificate}}</el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item v-show="propForm.clientLesseeType!=0" label="证件类型:">{{baseInfo.commercialCertificate}}</el-form-item>
            </el-col>
            <!-- 第一行第4列-->
            <el-col :span="6">
              <el-form-item label="证件号码:">{{propForm.certificateNum}}</el-form-item>
            </el-col>
            <!-- 第二行-->
            <!-- 如果不是 "个人"，则会将下面一行会显示出来-->
            <template v-show="propForm.clientLesseeType!=0">
              <el-col :span="6">
                <el-form-item label="法人代表:">{{propForm.legalPerson}}</el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="身份证号码:">{{propForm.legalIdentityCard}}</el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="手机号码:">{{propForm.phoneNum}}</el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="联系电话:">{{propForm.telephone}}</el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="详细地址:">{{propForm.address}}</el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="行业类别:">{{propForm.categroyEmployment}}</el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="产业引进部门:">{{propForm.introduceUnit}}</el-form-item>
              </el-col>
            </template>
          </el-row>
        </el-form>

        <div class="card-title">
          物业信息
          <el-button type="primary" size="small" @click="$refs.roomSelect.show('1')">添加物业</el-button>
        </div>
        <el-table class="mt20" :data="propertyInformation" stripe align="center">
          <el-table-column label="物业名称" align="center" prop="propertyName" width="150" />
          <el-table-column align="center" label="建筑面积（㎡）" prop="buildingArea" width="100" />
          <el-table-column align="center" prop="price" label="单价（元/㎡/月）" width="100">
            <template slot-scope="scope">
              <el-input v-model="scope.row.price" v-only-number="{min:0, max:10000, precision:2}" />
            </template>
          </el-table-column>
          <el-table-column align="center" prop="remarks" label="说明" width="100">
            <template slot-scope="scope">
              <el-input v-model="scope.row.remarks" maxlength="100" />
            </template>
          </el-table-column>
          <el-table-column align="center" width="80" label="操作">
            <template slot-scope="scope">
              <el-button @click="deleteList(scope.$index, 'propertyInformation')" type="text">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="card-title mt20">
          租金标准
          <el-button type="primary" size="small" @click="addFeeInformation">添加区间</el-button>
        </div>
        <el-form class="mt20" :model="rules_rentFeeInformation" :rules="rules_rentFeeInformation.rules" ref="rules_rentFeeInformation">
          <el-table :data="rules_rentFeeInformation.rentFeeInformation" stripe>
            <el-table-column prop="startDate" align="center" label="开始时间" width="100">
              <template slot-scope="scope">
                <el-form-item :prop="'rentFeeInformation.' + scope.$index + '.startDate'" :rules="rules_rentFeeInformation.rules.startDate">
                  <el-date-picker v-model="scope.row.startDate" type="date" value-format="yyyy-MM-dd" placeholder="选择开始日期" @change="handleDateIntervalChange" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="endDate" align="center" label="结束时间" width="100">
              <template slot-scope="scope">
                <el-form-item :prop="'rentFeeInformation.' + scope.$index + '.endDate'" :rules="rules_rentFeeInformation.rules.endDate">
                  <el-date-picker v-model="scope.row.endDate" type="date" value-format="yyyy-MM-dd" placeholder="选择结束日期" @change="handleDateIntervalChange" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="priceFinal" label="月租金" @change="calculateTheRent" align="center" width="100">
              <template slot-scope="scope">
                <el-form-item :prop="'rentFeeInformation.' + scope.$index + '.priceFinal'" :rules="rules_rentFeeInformation.rules.priceFinal">
                  <el-input @change="calculateTheRent" v-model.number="scope.row.priceFinal" v-only-number="{min:0, max:99999999, precision:2}" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column align="center" prop="remarks" label="说明" width="100">
              <template slot-scope="scope">
                <el-form-item>
                  <el-input v-model="scope.row.remarks" maxlength="100" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column width="100" label="操作" align="center">
              <template slot-scope="scope">
                <el-button @click.stop="deleteList(scope.$index, 'rules_rentFeeInformation','rentFeeInformation')" type="text">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form>

        <div class="card-title mt20">
          其他费用
          <el-button type="primary" size="small" @click="selectFeeItem">添加费用</el-button>
        </div>
        <el-table class="mt20" align="center" :data="contractFee" style="width: 100%">
          <el-table-column prop="chargeProjectName" align="center" label="费用项目名称" width="180">
            <template slot-scope="scope">
              <el-select v-model="scope.row.feeitemId" placeholder="请选择">
                <el-option v-for="item in charge_project_type" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column prop="feeStadard" align="center" label="缴费日期" width="180">
            <template slot-scope="scope">
              <el-date-picker v-model="scope.row.feeStadard" type="date" value-format="yyyy-MM-dd" placeholder="选择日期" />
            </template>
          </el-table-column>
          <el-table-column prop="amount" align="center" label="金额" width="180">
            <template slot-scope="scope">
              <el-input v-model.number="scope.row.amount" v-only-number="{min:0, max:99999999, precision:2}" />
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="180">
            <template slot-scope="scope">
              <el-button @click.stop="deleteList(scope.$index, 'contractFee')" type="text">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="card-title mt20">合同信息</div>

        <el-form :model="formData" class="basicPadding mt20 reset" size="small" :rules="rules_formData" ref="formData">
          <el-row :gutter="30">
            <el-col :span="6">
              <el-form-item label="合同编号" prop="contractCode">
                <el-input placeholder="请输入" v-model="formData.contractCode" maxlength="40" />
              </el-form-item>
            </el-col>

            <el-col :span="6">
              <el-form-item label="签订方式" prop="signType">
                <el-select v-model="formData.signType" placeholder="请选择">
                  <el-option v-for="item in rentSigningMethod" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="6">
              <el-form-item label="收费方式" prop="feeType">
                <el-select v-model="formData.feeType" placeholder="请选择">
                  <el-option v-for="item in rentFeeType" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="6" v-if="isFeeTypeValue">
              <el-form-item label="自定义收费周期（输入的数字代表收租周期）" prop="feeTypeValue">
                <el-input v-model.number="formData.feeTypeValue" placeholder="请输入" v-only-number="{min:0, max:31, precision:2}" />
              </el-form-item>
            </el-col>

            <el-col :span="6">
              <el-form-item label="应收日（输入数字代表每月应收日期）" prop="feeDate">
                <el-input v-model.number="formData.feeDate" placeholder="请输入应收日" v-only-number="{min:0, max:31, precision:2}" />
              </el-form-item>
            </el-col>

            <el-col :span="6">
              <el-form-item label="合同签订日期" prop="signDate">
                <el-date-picker v-model="formData.signDate" type="date" value-format="yyyy-MM-dd" placeholder="选择日期" />
              </el-form-item>
            </el-col>

            <el-col :span="6">
              <el-form-item label="合同开始日期" prop="startDate">
                <el-date-picker v-model="formData.startDate" type="date" value-format="yyyy-MM-dd" placeholder="选择日期" />
              </el-form-item>
            </el-col>

            <el-col :span="6">
              <el-form-item label="合同结束日期" prop="endDate">
                <el-date-picker v-model="formData.endDate" type="date" value-format="yyyy-MM-dd" placeholder="选择日期" />
              </el-form-item>
            </el-col>

            <el-col :span="6">
              <el-form-item label="装修免租期" prop="freeFees">
                <el-date-picker v-model="freeFees" type="daterange" value-format="yyyy-MM-dd" />
              </el-form-item>
            </el-col>

            <el-col :span="6">
              <el-form-item label="起租日期" prop="rentStartDate">
                <el-date-picker v-model="formData.rentStartDate" type="date" value-format="yyyy-MM-dd" placeholder="选择日期" />
              </el-form-item>
            </el-col>

            <el-col :span="6">
              <el-form-item label="合同类型" class="block">
                <el-input readonly :value="rentContractTypeName" />
              </el-form-item>
            </el-col>

            <el-col :span="6">
              <el-form-item label="合同细类" class="block">
                <el-input readonly :value="rentContractSubTypeName" />
              </el-form-item>
            </el-col>

            <el-col :span="6">
              <el-form-item label="建筑面积" prop="buildingArea">
                <el-input v-model="formData.buildingArea" :min="0" v-only-number="{min:1, max:99999999, precision:2}" />
              </el-form-item>
            </el-col>

            <el-col :span="6">
              <el-form-item label="月租金" prop="rentAmount">
                <el-input v-model="formData.rentAmount" v-only-number="{min:0, max:99999999, precision:2}" />
              </el-form-item>
            </el-col>

            <el-col :span="6" v-if="false">
              <el-form-item label="审批方式" prop="approveType">
                <el-select v-model="formData.approveType" placeholder="请选择">
                  <el-option v-for="item in rentContractApproveType" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="6">
              <el-form-item label="管理所" prop="administrativeOffice">
                <el-select v-model="formData.administrativeOffice" placeholder="请选择">
                  <el-option v-for="item in administrativeOffice" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="6" v-if="false">
              <el-form-item label="产业引进部门" prop="importDept">
                <el-input placeholder="请输入产业引进部门" v-model="formData.importDept" />
              </el-form-item>
            </el-col>

            <el-col :span="6" v-if="false">
              <el-form-item label="地址" prop="address">
                <el-input placeholder="请输入地址" v-model="formData.address" />
              </el-form-item>
            </el-col>

            <el-col :span="6">
              <el-form-item label="备注" prop="remarks">
                <el-input placeholder="请输入内容" v-model="formData.remarks" maxlength="100" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>

        <!-- 承租方选择 -->
        <client-select ref="clientSelect" :multiple="false" @completeSelect="handleClientChoose" />
        <!-- 物业选择 -->
        <room-select ref="roomSelect" :disabledArr="propertyInformation.map(item => item.roomId)" @completeSelect="handlePropertyChoose" />
      </div>
      <!-- 上传文件 -->
      <div slot="step2" class="step2">
        <h3>文件上传</h3>
        <div class="uploadWrap">
          <v-upload
            ref="rentContractFileUpload"
            :busId="formData.rentContractId"
            modelType="rent-contract"
            @onSuccess="uloadCompleted"
            v-model="uploadFileList"
            multiple
          />
        </div>
      </div>
      <!-- 智能计费 -->
      <div slot="step3" class="step3">
        <h3>收费明细</h3>
        <el-table :data="receivableFees">
          <el-table-column prop="costMonth" label="所属月份" width="180" />
          <el-table-column prop="chargeProjectName" label="收费项目" width="180" />
          <el-table-column prop="costPeriodStart" label="开始日期" width="180" />
          <el-table-column prop="costPeriodEnd" label="结束日期" width="180" />
          <el-table-column prop="receivableDate" label="应收日期" width="180" />
          <el-table-column prop="receivableMoney" label="应收金额" width="180" />
        </el-table>
      </div>
    </v-step>
  </div>
</template>
<script>
import { addObj, getObj, putObj, delObj, getGenerateFeeObj, saveUrl, presend, uploadContractFile, } from '../api/rent-contract'
import { getObj as getClientManage } from '@/views/client-manage/api/clientlessee'
import clientSelect from '@/components/comm-select/client-select'
import roomSelect from '@/components/comm-select/room-select'
import { getDict } from '@/utils'
import pdf from 'vue-pdf'
import vPdf from '@/components/v-pdf'
import moment from 'moment'
export default {
  components: { clientSelect, roomSelect, pdf, vPdf },
  beforeMount () {
    //判断编辑和新增
    const { id, type, subtype } = this.$route.query

    if (id) {
      this.formData.rentContractId = id
      // 获取合同数据
      this.showContractData(id)
    } else {
      if (!type || !subtype) {
        this.$router.back()
        return
      }
      this.type = type
      this.subType = subtype
      this.formData.type = type
      this.formData.subType = subtype
    }
  },
  data () {
    return {
      // 合同主类
      type: '',
      // 合同子类
      subType: '',
      // 模板文件
      fileList: [],
      // 合同名称表单
      nameForm: {
        contractName: '',
      },
      // 展示的模板附件地址
      pdfUrl: '',
      // 展示的数据格式
      fileType: '',
      // 模板pdf弹窗展示地址
      dialogContractVisible: false,
      // 合同基础信息表单
      formData: {
        customerId: '', //承租方id
        customerName: '', //承租方名称
        rentContractId: '', //合同id
        contractName: '', //合同名称
        contractCode: '', //合同编码
        contractUrl: '', //合同url
        signType: '', //签定方式
        signDate: '', //合同签订日期
        feeTypeValue: 1, //自定义收费时间
        feeDate: '', //应收日
        startDate: '', //合同开始时间
        endDate: '', //合同结束时间
        rentStartDate: '', //起租日期
        freeFeeStart: '',
        freeFeeEnd: '',
        type: '', //合同类型
        subType: '', //合同细类
        buildingArea: '', //建筑总面积
        rentAmount: '', //总月租金
        feeType: '', //计费方式
        approveType: '', //审批方式
        administrativeOffice: '', //管理所
        importDept: '', //产业引进部门
        address: '', //地址
        remarks: '', //备注
        category: 1, //租赁合同标志
      },
      // 承租方类型
      clientLesseeType: '',
      //承租方信息
      propForm: {
        clientLesseeType: '',
        clientLesseeName: '',
      },
      // 基础信息
      baseInfo: {
        // 承租方
        lessee: '',
        // 供应商
        provider: '',
        // 工商证件
        commercialCertificate: '',
        // 个人证件
        personageCertificate: '',
      },
      //物业信息
      propertyInformation: [],
      //租金信息
      rules_rentFeeInformation: {
        rentFeeInformation: [],
        rules: {
          startDate: [
            { required: true, message: '请选择开始时间', trigger: 'blur' },
            { validator: this.validateStartDate, trigger: 'blur' },
          ],
          endDate: [
            { required: true, message: '请选择结束时间', trigger: 'blur' },
            { validator: this.validateEndDate, trigger: 'blur' },
          ],
          priceFinal: [
            { required: true, message: '请输入月租金', trigger: 'blur' },
          ],
        },
      },
      // 免租时间
      freeFees: [],
      //其他费用
      contractFee: [],
      // 上传附件列表
      uploadFileList: [],
      // 费用预览
      receivableFees: [],

      //合同表单校验规则
      rules_formData: {
        customerId: [
          { required: true, message: '承租方不能为空', trigger: 'blur' },
        ],
        contractCode: [
          { required: true, message: '合同编号不能为空', trigger: 'blur' },
        ],
        signType: [
          { required: true, message: '签订方式不能为空', trigger: 'blur' },
        ],
        signDate: [
          { required: true, message: '合同签订日期不能为空', trigger: 'blur' },
        ],
        startDate: [
          { required: true, message: '合同开始日期不能为空', trigger: 'blur' },
        ],
        endDate: [
          { required: true, message: '合同结束日期不能为空', trigger: 'blur' },
        ],
        rentStartDate: [
          { required: true, message: '起租日期不能为空', trigger: 'blur' },
        ],
        feeType: [
          { required: true, message: '请选择收费方式', trigger: 'blur' },
        ],
        feeDate: [
          {
            required: true,
            message: '请输入1到31之间的数字代表每月收租时间',
            trigger: 'blur',
          },
        ],
        administrativeOffice: [
          { required: true, message: '请选择管理所', trigger: 'blur' },
        ],
      },
    }
  },
  computed: {
    // 步骤列表
    milepost () {
      return [
        { title: '选择模板', validate: this.handleChooseTemplate },
        { title: '合同基础信息填写', validate: this.contractValidate },
        { title: '上传文件', validate: this.uploadValidate },
        { title: '智能计费', validate: this.handleCompleted },
      ]
    },
    // 判断是否展示模板
    showTemplate () {
      if (!this.pdfUrl) return false
      if (/^blob/.test(this.pdfUrl)) return true
      if (this.pdfUrl.split('.').pop() != 'pdf') return false
      return true
    },
    // 是否显示自定义收费周期
    isFeeTypeValue () {
      return this.formData.feeType == '6'
    },
    //收费项目
    charge_project_type () {
      return getDict('charge_project_type')
    },
    //调价方式
    rentPriceRejustType () {
      return getDict('rent_price_rejust_type')
    },
    //证件类型
    rentCertificateType () {
      return getDict('rent_certificate_type')
    },
    //签订方式
    rentSigningMethod () {
      return getDict('rent_signing_method')
    },
    //收费方式
    rentFeeType () {
      return getDict('rent_fee_type')
    },
    //审批方式
    rentContractApproveType () {
      return getDict('rent_contract_approve_type')
    },
    //管理所
    administrativeOffice () {
      return getDict('administrative_office')
    },
    //承租方类型
    lesseeType () {
      return getDict('lessee_type')
    },
    //供应商类型
    providerType () {
      return getDict('provider_type')
    },
    //个人证件类型
    personageCertificateType () {
      return getDict('personage_certificate_type')
    },
    //工商证件类型
    commercialCertificateType () {
      return getDict('commercial_certificate_type')
    },
    // 合同细类名称
    rentContractSubTypeName () {
      if (!this.subType) return ''
      let subTypes = getDict('rent_contract_sub_type')
      let subType = subTypes.find((item) => item.value == this.subType)
      return subType ? subType.label : ''
    },
    //合同类型名称
    rentContractTypeName () {
      if (!this.type) return ''
      let types = getDict('rent_contract_type')
      let type = types.find((item) => item.value == this.type)
      return type ? type.label : ''
    },
  },
  watch: {
    // 免租日期监听
    freeFees () {
      if (this.freeFees.length > 1) {
        const [freeFeeStart, freeFeeEnd] = this.freeFees
        this.formData.freeFeeStart = this.getDate(freeFeeStart)
        this.formData.freeFeeEnd = this.getDate(freeFeeEnd)
        //起租日期等免租结束加1
        if (
          this.formData.freeFeeEnd != null &&
          this.formData.freeFeeEnd != ''
        ) {
          let tempDate = Date.parse(this.formData.freeFeeEnd)
          tempDate = tempDate + 1000 * 60 * 60 * 24
          let tempDate2 = new Date(tempDate)
          this.formData.rentStartDate = this.getDate(tempDate2)
        }
      }
    },
  },
  methods: {
    // 一、选择模板
    async handleChooseTemplate () {
      //1、判断有无文件上传
      if (this.fileList.length) {
        // 合同附件上传
        let formData = new FormData()
        formData.append('file', this.fileList[0].raw)
        formData.append('module', 'rentContract')
        formData.append('busId', this.$route.query.id || '')
        const res = await uploadContractFile(formData)
        if (res.data.code == 0) {
          //this.pdfUrl = window.location.origin + res.data.data.url;
          this.formData.contractUrl = res.data.data.url
          this.formData.contractName = this.nameForm.contractName
        }
      }
      // 2、判断当前是新增还是编辑
      // 编辑
      if (this.$route.query.id) {
        const { rentContractId, contractUrl, type, subType } = this.formData
        const { contractName } = this.nameForm
        let response = await saveUrl({
          rentContractId,
          contractName,
          contractUrl,
          type,
          subType,
        })
        if (response.data.code == 0) {
          this.$alert('请阅读合同信息，根据实际情况编辑合同内容')
          this.$refs.steps.next()
        }
      } else {
        // 新增
        let requestData = {
          contractName: this.nameForm.contractName,
          contractUrl: this.formData.contractUrl,
          type: this.type,
          subType: this.subType,
          category: 1
        }
        const response = await addObj(requestData)
        if (response.data.code == 0) {
          this.$alert('合同初始信息创建成功，请补充合同详细信息')
          this.formData.rentContractId = response.data.data
          this.showContractData(response.data.data)
          this.$refs.steps.next()
        }
      }
      return false
    },
    // 二、合同基础信息填写
    async contractValidate () {
      if (!this.formData.customerId) {
        this.$message.error('请选择承租方')
        return false
      }

      if (
        !this.propertyInformation.length ||
        !this.rules_rentFeeInformation.rentFeeInformation.length
      ) {
        this.$message.error('物业信息和租金标准都至少填写一条数据')
        return false
      }

      const rentFeeVerify = await this.$refs.rules_rentFeeInformation.validate()
      if (!rentFeeVerify) {
        this.$message.error('租金标准验证不通过，请按要求填写')
        return false
      }

      const formDataVerify = await this.$refs.formData.validate()
      if (!formDataVerify) {
        this.$message.error('租金标准验证不通过，请按要求填写')
        return false
      }

      //合同开始日期不能大于结束日期
      if (this.formData.startDate > this.formData.endDate) {
        this.$message.error('合同结束日期不能小于开始日期')
        return false
      }

      //租金子表的验证，开始日期不能大于结束日期
      if (
        this.rules_rentFeeInformation.rentFeeInformation.some(
          (item) => item.startDate > item.endDate
        )
      ) {
        this.$message.error('租金标准中区间的结束日期不能小于开始日期')
        return false
      }

      //承租方不能为空
      if (!this.formData.customerName) {
        this.$message.error('承租方不能为空')
        return false
      }

      //合同名称赋过去
      this.formData.contractName = this.nameForm.contractName

      let requestData = {
        ...this.formData,
        rentContractDetails: this.rules_rentFeeInformation.rentFeeInformation,
        rentContractProfee: this.contractFee,
        rentContractRooms: this.propertyInformation,
        category: 1
      }
      const putResult = await putObj(requestData)
      if (putResult.data.code == 0) {
        this.$refs.steps.next()
      }
      return false
    },
    // 三、上传文件
    uploadValidate () {
      if (this.uploadFileList.length) {
        this.$refs.rentContractFileUpload.submit()
      } else {
        this.preViewFee()
        this.$refs.steps.next()
      }
    },
    // 四、上传完成
    async handleCompleted () {
      const response = await presend(this.formData.rentContractId)
      if (response.data.code == 0) {
        this.$router.push('/wy-rent/contract/list')
      }
      return false
    },
    // 模板展示点击
    previewTemplate () {
      if (this.previewType == 'pdf') {
        this.dialogContractVisible = true
      } else {
        window.location.href = this.pdfUrl
      }
    },

    // 监听上传模板
    handleTemplateChange (file, fileList) {
      // 如果当前场景是新增
      const previewType = file.name.split('.').pop()
      this.previewType = previewType

      let url = window.URL.createObjectURL(file.raw)
      this.pdfUrl = url

      this.fileList = [file]

      this.$alert('模板替换成功，请点击下一步保存新的模板附件')
    },
    // 获取合同数据
    async showContractData (id) {
      // 获取合同数据
      const res = await getObj(id)
      if (res.data.code == 0) {
        const { data } = res.data
        this.formData = { ...this.formData, ...data }
        // 租金信息
        this.rules_rentFeeInformation.rentFeeInformation =
          data.rentContractDetails
        // 物业信息
        this.propertyInformation = data.rentContractRooms
        // 其他费用
        this.contractFee = data.rentContractProfees
        // 合同名称
        this.nameForm.contractName = data.contractName
        // 设置预览的pdf地址
        if (data.contractUrl) {
          this.pdfUrl = window.location.origin + data.contractUrl
          this.previewType = data.contractUrl.split('.').pop()
        }

        // 编辑场景设置表单的合同类型
        if (!this.type) {
          this.type = data.type
        }
        if (!this.subType) {
          this.subType = data.subType
        }
      }

      //免租期
      this.freeFees = []
      if (this.formData.freeFeeStart) {
        this.freeFees[0] = this.formData.freeFeeStart
      }
      if (this.formData.freeFeeEnd) {
        this.freeFees[1] = this.formData.freeFeeEnd
      }

      //获得承租方信息
      if (this.formData.customerId != null) {
        const propForm = await getClientManage(this.formData.customerId)
        this.propForm = propForm.data.data
        this.clientLesseeType = propForm.data.data.clientLesseeType
      }
      this.showlessee()
    },
    // 获取费用预览数据
    async preViewFee (id) {
      const res = await getGenerateFeeObj(this.formData.rentContractId)
      if (res.data.code == 0) {
        this.receivableFees = res.data.data
      }
    },
    //展示证件类型
    showlessee () {
      const { clientLesseeType, providerType, certificateType } = this.propForm
      let lessee = this.lesseeType.find(
        (item) => item.value == clientLesseeType
      )
      let provider = this.providerType.find(
        (item) => item.value == providerType
      )
      let personageCertificate = this.personageCertificateType.find(
        (item) => item.value == certificateType
      )
      let commercialCertificate = this.commercialCertificateType.find(
        (item) => item.value == certificateType
      )
      this.baseInfo = {
        lessee: lessee ? lessee.label : '',
        provider: provider ? provider.label : '',
        personageCertificate: personageCertificate
          ? personageCertificate.label
          : '',
        commercialCertificate: commercialCertificate
          ? commercialCertificate.label
          : '',
      }
    },
    // 添加租金标准区间
    addFeeInformation () {
      this.rules_rentFeeInformation.rentFeeInformation.push({
        startDate: '',
        endDate: '',
        priceFinal: '',
        remarks: '',
      })
    },
    // 添加其他费用
    selectFeeItem () {
      this.contractFee.push({
        feeitemId: '',
        chargeProjectName: '',
        feeStadardCode: '',
        feeStadard: '',
        amount: '',
      })
    },
    // 月租金改变监听
    calculateTheRent () {
      this.formData.rentAmount = this.rules_rentFeeInformation.rentFeeInformation[0].priceFinal
    },
    // 监听承租方选择
    handleClientChoose (selectedData) {
      this.propForm = selectedData[0]
      this.formData.customerId = this.propForm.clientLesseeId
      this.formData.customerName = this.propForm.clientLesseeName
      this.showlessee()
    },
    // 监听物业选择
    handlePropertyChoose (selectedData) {
      this.formData.buildingArea = 0
      let dataList = selectedData.map((item) => {
        const { roomId, buildingArea, propertyName, price } = item
        return {
          roomId,
          buildingArea,
          propertyName,
          assessPrice: price,
          price: '',
          remarks: '',
        }
      })
      let propertyInformation = [...this.propertyInformation, ...dataList]
      this.propertyInformation = propertyInformation
      this.formData.buildingArea = propertyInformation.reduce(
        (total, item) => total + item.buildingArea,
        0
      )
    },
    // 第三步附件上传完成回调
    uloadCompleted (response) {
      this.$message.success('附件提交成功')
      this.preViewFee()
      this.$refs.steps.next()
    },
    // 列表删除监听
    deleteList (index, type, subType = '') {
      if (subType) {
        this[type][subType].splice(index, 1)
      } else {
        this[type].splice(index, 1)
      }
    },
    //将date类型转换为yyyy-MM-dd
    getDate (strDate) {
      var date = new Date(strDate)
      var returnValue = date.getFullYear()
      if (date.getMonth() + 1 < 10) {
        returnValue += '-0' + (date.getMonth() + 1)
      } else {
        returnValue += '-' + (date.getMonth() + 1)
      }
      if (date.getDate() < 10) {
        returnValue += '-0' + date.getDate()
      } else {
        returnValue += '-' + date.getDate()
      }
      return returnValue
    },
    // 租金标准时间校验-开始时间
    validateStartDate (rule, value, callback) {
      let index = rule.field.split('.')[1]
      let dateList = this.rules_rentFeeInformation.rentFeeInformation
      // 判断结束时间是否存在并且当前时间是否大于结束时间
      if (
        dateList[index].endDate &&
        moment(value).isAfter(dateList[index].endDate)
      ) {
        return callback(new Error('开始时间不能大于结束时间'))
      }
      // 判断数组的长度是否大于1，判断时间是否和重叠
      if (
        dateList.length > 1 &&
        dateList.some(
          (item, current) =>
            current != index &&
            moment(value).isBetween(item.startDate, item.endDate, null, '[]')
        )
      ) {
        return callback(new Error('时间区间不能重叠'))
      }
      return callback()
    },
    // 租金标准时间校验-结束时间
    validateEndDate (rule, value, callback) {
      let index = rule.field.split('.')[1]
      let dateList = this.rules_rentFeeInformation.rentFeeInformation
      if (
        dateList[index].startDate &&
        moment(value).isBefore(dateList[index].startDate)
      ) {
        return callback(new Error('结束时间不能小于开始时间'))
      }
      if (
        dateList.length > 1 &&
        dateList.some(
          (item, current) =>
            current != index && moment(value).isBetween(
              item.startDate,
              item.endDate,
              null,
              '[]'
            )
        )
      ) {
        return callback(new Error('时间区间不能重叠'))
      }
      return callback()
    },
    // 监听租金标准，设置合同信息的开始日期/结束日期/起租日期
    handleDateIntervalChange () {
      let dateList = this.rules_rentFeeInformation.rentFeeInformation
      // 如果租金标准条数只有一条，取第一条，否则计算获取最小时间和最大时间
      let date =
        dateList.length <= 1
          ? dateList[0]
          : dateList.reduce(
            (total, item) => {
              let { startDate, endDate } = total
              if (
                !startDate ||
                (item.startDate && moment(item.startDate).isBefore(startDate))
              ) {
                startDate = item.startDate
              }
              if (
                !endDate ||
                (item.endDate && moment(item.endDate).isAfter(endDate))
              ) {
                endDate = item.endDate
              }
              return { startDate, endDate }
            },
            { startDate: '', endDate: '' }
          )

      this.formData.startDate = date.startDate
      this.formData.rentStartDate = date.startDate
      this.formData.endDate = date.endDate
    },
  },
}
</script>

<style scoped lang="scss">
// 导入步骤
.importStep {
  .templateUpload {
    width: 400px;
    margin: 40px auto 0;
    .icon {
      width: 136px;
      height: 136px;
      border-radius: 50%;
      border: 2px solid #e3e3e4;
      display: flex;
      justify-content: center;
      align-items: center;
      margin: 0 auto;
    }
    .elIcon {
      font-size: 70px;
      color: #999;
    }
    p {
      font-size: 14px;
      margin-top: 20px;
      color: #333;
    }
    .exportBtn {
      width: 145px;
      height: 48px;
      font-size: 15px;
      margin-top: 20px;
    }
    .el-upload__tip {
      font-size: 13px;
      color: #999;
    }
  }
  .nameForm {
    display: none;
    width: 600px;
    margin: 40px auto;
  }
  .templateShow {
    padding: 0 20px;
    display: flex;
    justify-content: center;
    .fileWrap {
      width: 400px;
      height: 450px;
      border: 1px solid #eaeaea;
      transition: 0.5s;
      margin-right: 22px;
      overflow: hidden;
      display: flex;
      align-items: center;
      cursor: pointer;
      &:hover {
        box-shadow: 0 0 35px rgba(0, 0, 0, 0.07);
      }
      /deep/ .upload-demo {
        width: 100%;
        height: 100%;
      }
      /deep/ .el-upload {
        width: 100%;
        height: 100%;
      }
      .add {
        width: 100%;
        height: 100%;
        display: flex;
        justify-content: center;
        align-items: center;
        flex-direction: column;
        .icon {
          margin: 0 auto;
          font-size: 60px;
          color: #ccc;
        }
      }
      .el-upload__tip {
        color: #999;
        margin-top: 20px;
        font-size: 13px;
      }
    }
  }
  .wordsWrap {
    width: 100%;
    height: 100%;
    padding: 50px 0 50px;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    align-items: center;
    p {
      margin-top: 10px;
    }
  }
}
// 基本信息编写
.step1 {
  .basicPadding {
    padding: 0 22px;
  }
  .mt20 {
    margin-top: 20px;
  }
  /deep/ .el-form.reset {
    .el-form-item {
      display: flex;
      flex-wrap: wrap;
      height: 65px;
    }
    .el-form-item__label {
      width: 100%;
      float: none;
      text-align: left;
    }
    .el-form-item__content {
      width: 100%;
      text-align: left;
    }
  }
}
// 上传文件&&数据回显
.step2,
.step3 {
  padding: 0px 22px 20px;
  text-align: left;
  min-height: 300px;
  h3 {
    margin-bottom: 22px;
    color: #666666;
    font-weight: 600;
    border-bottom: 1px solid #dee2e6;
    line-height: 50px;
    font-size: 16px;
  }
}
</style>

